package aole.visq.draw;

import jpen.PButton;
import jpen.PButtonEvent;
import jpen.PKind;
import jpen.PKindEvent;
import jpen.PLevel;
import jpen.PLevelEvent;
import jpen.event.PenAdapter;

public class ProcessPen extends PenAdapter {
	private boolean	bIsDown;
	private int		lx, ly;
	private boolean	wasCursor	= true;
	private DrawApp	app;
	private PKind	lastKind;

	public ProcessPen( DrawApp a ) {
		app = a;
	}

	public void penLevelEvent( PLevelEvent evt ) {
		int x = (int) evt.pen.getLevelValue( PLevel.Type.X );
		int y = (int) evt.pen.getLevelValue( PLevel.Type.Y );
		if( (lx) == (x) && (ly) == (y) ) return;
		if( wasCursor )
			app.inputMove( lx, ly, 1 );
		else app.inputMove( x, y, evt.pen.getLevelValue( PLevel.Type.PRESSURE ) );
		lx = x;
		ly = y;
	}

	public void penButtonEvent( PButtonEvent evt ) {
		lx = (int) evt.pen.getLevelValue( PLevel.Type.X );
		ly = (int) evt.pen.getLevelValue( PLevel.Type.Y );
		// See if the pen is down
		boolean tmp = evt.pen.hasPressedButtons();
		if( bIsDown ) {
			if( !tmp ) {
				// pen is up
				app.inputUp( lx, ly );
				bIsDown = tmp;
			}
		} else {
			if( tmp ) {
				// get button
				// 1: left
				// 2: right
				int btn = 0;
				if( evt.pen.getButtonValue( PButton.Type.LEFT ) )
					btn = 1;
				else if( evt.pen.getButtonValue( PButton.Type.RIGHT ) )
					btn = 2;
				else return;

				// pen is down
				app.inputDown( lx, ly, btn );
				bIsDown = tmp;
			}
		}
	}

	@Override
	public void penKindEvent( PKindEvent evt ) {
		// get kind of input
		// 1: stylus
		// 2: eraser
		// 3: cursor
		PKind type = evt.pen.getKind();

		if( type == PKind.valueOf( PKind.Type.STYLUS ) ) {
			if( lastKind != type ) app.setBrush();
			lastKind = type;
			wasCursor = false;
		} else if( type == PKind.valueOf( PKind.Type.ERASER ) ) {
			if( lastKind != type ) app.setEraser();
			lastKind = type;
			wasCursor = false;
		} else if( type == PKind.valueOf( PKind.Type.CURSOR ) ) {
			lastKind = type;
			wasCursor = true;
		}
	}
}